package com.qk.management.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.constant.ClueTrackRecordType;
import com.qk.common.constant.ClueTrackRecordTypeConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.clue.ClueDO;
import com.qk.domain.clue.CluePoolDO;
import com.qk.domain.user.UserDO;
import com.qk.dto.clue.*;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.ClueTrackRecordMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.ClueService;
import com.qk.vo.clue.ClueVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @Author: ZgYn
 * @Date 2025/10/13 16:56
 * @name：ClueServiceImpl
 */
@Slf4j
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;
    @Autowired
    private BusinessMapper businessMapper;


    @Override
    public PageResult<ClueDO> clueListMp(ClueListDTO dto) {
        log.info("开始查询线索列表，参数：{}", dto);
        try {
            Page<Object> page = new Page<>(dto.getPage(), dto.getPageSize());
            log.info("设置分页参数成功");

            Page<ClueDO> clueDOList = this.baseMapper.selectByPageMp(page, dto);
            return PageResult.<ClueDO>builder()
                    .total(Long.valueOf(clueDOList.getTotal()).intValue())
                    .rows(clueDOList.getRecords())
                    .build();
        } catch (Exception e) {
            log.error("查询线索列表失败：", e);
            throw e;
        }


    }


    @Override
    public PageResult<ClueDO> clueList(ClueListDTO dto) {

        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<ClueDO> clueDOList = this.baseMapper.selectByPage(dto);
        log.info("查询结果数量：{}", clueDOList != null ? clueDOList.size() : 0);
        Page<ClueDO> clueInfo = (Page<ClueDO>) clueDOList;
        return PageResult.<ClueDO>builder()
                .total(Long.valueOf(clueInfo.getTotal()).intValue())
                .rows(clueDOList)
                .build();

    }


    @Override
    public void save(ClueDTO clueDTO) {
        if (ObjectUtil.isEmpty(clueDTO.getPhone()) || ObjectUtil.isEmpty(clueDTO.getChannel())) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Clue clue = BeanUtil.copyProperties(clueDTO, Clue.class);
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        this.save(clue);
    }

    @Override
    public ClueVO getClueById(Integer clueId) {
        Clue clue = this.baseMapper.selectById(clueId);
        Integer userId = clue.getUserId();
        UserDO user = userMapper.selectById(userId);
        List<ClueTrackRecord> clueTrackRecords = clueTrackRecordMapper.selectList(Wrappers.lambdaQuery(ClueTrackRecord.class).in(ClueTrackRecord::getClueId, clueId));
        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);

        List<ClueVO.ClueTrackRecordVO> list = clueTrackRecords.stream().map(item -> {
            ClueVO.ClueTrackRecordVO vo = BeanUtil.copyProperties(item, ClueVO.ClueTrackRecordVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        clueVO.setTrackRecords(list);
        return clueVO;
    }

    @Transactional
    @Override
    public void updateClue(UpdateClueInfoDTO updateClueInfoDTO) {
        Clue clue = BeanUtil.copyProperties(updateClueInfoDTO, Clue.class);
        clue.setUpdateTime(LocalDateTime.now());
        if (Objects.equals(updateClueInfoDTO.getStatus(), ClueStatusConstants.FOLLOW_UP)) {
            clue.setStatus(ClueStatusConstants.FOLLOWING);
        }
        Integer userId = CurrentUserContextHolders.get();
        clue.setUserId(userId);
        this.updateById(clue);
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(updateClueInfoDTO, ClueTrackRecord.class);
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(clue.getId());
        clueTrackRecord.setType(ClueTrackRecordType.NORMAL);
        clueTrackRecord.setUserId(userId);
        clueTrackRecordMapper.insert(clueTrackRecord);
    }

    @Override
    public void toBusiness(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        clue.setStatus(ClueStatusConstants.TO_BUSINESS);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);

        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setId(null);
        business.setUserId(null);
        business.setNextTime(null);
        business.setClueId(clue.getId());
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setStatus(BusinessStatusConstants.TO_BE_ASSIGNED);
        businessMapper.insert(business);
    }

    @Override
    @Transactional
    public void fakeClue(Integer id, FakeClueDTO dto) {
        this.baseMapper.updateById(Clue.builder()
                .id(id)
                .updateTime(LocalDateTime.now())
                .status(ClueStatusConstants.FAKE_CLUE)
                .build());
        clueTrackRecordMapper.insert(ClueTrackRecord.builder()
                .clueId(id)
                .type(ClueTrackRecordTypeConstants.FAKE_CLUE)
                .createTime(LocalDateTime.now())
                .userId(CurrentUserContextHolders.get())
                .record(dto.getRemark())
                .falseReason(dto.getReason())
                .build());
    }

    @Override
    public PageResult<CluePoolDO> cluePoolList(CluePoolDTO dto) {
        Page<Object> page = new Page<>(dto.getPage(), dto.getPageSize());

        List<CluePoolDO> list = this.baseMapper.selectPool(page, dto);
        return PageResult.<CluePoolDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(list)
                .build();
    }

}
